import React, {Component, PropTypes} from 'react'
import {
    Col,
    Form,
    Input,
    message,
    Modal,
    Table,
    Checkbox,
} from 'antd'
import {fetchPost} from '../../utils/request'
import Style from "./Index.less";
const {TextArea} = Input;

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;

class feedback extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            visible: false,
            feedList: [],
            loading: false,
            adminList: [],
            bucketTagList: [],
            userLanguageTagList: [],
            checkedList: [],
            indeterminate: true,
            checkAll: false,
            bucketTagDisabled: false,
            choseContent: "",
            page: {
                currentPage: 1,
                pageSize: 30,
                totalCount: 0
            },
            historyList: []
        }

    }

    componentDidMount() {
        this.getData();
    }

    componentWillReceiveProps(props) {

    }

    // 获取表格数据
    getData() {
        fetchPost(`/feedback/list/0?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`).then((res) => {
            console.log(res.data);
            if (res.code === 0) {
                if (res.data !== null) {
                    this.setState({
                        feedList: res.data.list,
                        page: {
                            ...this.state.page,
                            totalCount: res.data.page.totalCount || 0
                        },
                    })
                }
            } else {
                message.error(res.msg)
            }
        })
    }

    handleOk = (e) => {
        let self = this;
        this.props.form.validateFields((error, values) => {
            console.log(values);
            if (!error) {
                let params = {
                    feedId: values.feedbackId,
                    record: values.record,
                    send: 1
                }
                fetchPost('/feedback/record/save', params).then((res) => {
                    if (res.code === 0) {
                        message.info(res.msg, 0.2, () => {
                            this.setState({
                                visible: false,
                            }, () => {
                                this.getData()
                            })
                        })
                        this.props.form.resetFields()
                    } else {
                        message.error(res.msg)
                    }
                })
            }
        })
    }

    handleCancel = (e) => {
        let self = this;
        this.props.form.validateFields((error, values) => {
            console.log(values);
            if (!error) {
                let params = {
                    feedId: values.feedbackId,
                    record: values.record,
                    send: 0
                }
                fetchPost('/feedback/record/save', params).then((res) => {
                    if (res.code === 0) {
                        message.info(res.msg, 0.2, () => {
                            this.setState({
                                visible: false,
                            }, () => {
                                this.getData()
                            })
                        })
                        this.props.form.resetFields()
                    } else {
                        message.error(res.msg)
                    }
                })
            }
        })
    }


    edit = record => {
        this.setState({
            bucketTagDisabled: false,
        })
        this.props.form.setFieldsValue({
            feedbackId: record.id
        })

        this.getListByUserCode(record.userCode);
        this.setState({
            visible: true,
            choseContent: record.content
        });
    };

    getListByUserCode(useCode) {
        fetchPost(`/feedback/historyList/` + useCode).then((res) => {
            console.log(res.data);
            if (res.code === 0) {
                if (res.data !== null) {
                    this.setState({
                        historyList: res.data.list
                    })
                }
            } else {
                message.error(res.msg)
            }
        })
    }

    setPagination() {
        let self = this
        return {
            total: this.state.page.totalCount,
            pageSize: this.state.page.pageSize,
            showSizeChanger: false,
            showQuickJumper: true,
            showTotal(total) {
                return `Total ${total} `
            },
            onChange(current) {
                self.nextPage(current)
            }
        }
    }

    nextPage(currentPage) {
        this.setState({
            page: {
                ...this.state.page,
                currentPage
            }
        }, () => {
            this.getData()
        })
    }

    getRowKey(record) {
        return record.content
    }


    createDialog() {
        var messages = [];
        this.state.historyList.map(h => {
            if (h.content != "")
                messages.push(this.getCustomerMessage(h.content));
            if (h.handlerLog != "")
                messages.push(this.getCsMessage(h.handlerLog));
        })

        return messages;
    }

    getCustomerMessage(content) {
        return <div style={{"margin-top": 12, display: "inline-block", width: "100%"}}>
            <div style={{width: 20, float: "left"}}>
                <img style={{width: 20, height: 20}}
                     src="http://cashmama-oss-pro.cashmama.in/app/customer_black.png"/>

            </div>
            <div style={{"margin-left": 22, "line-height": 19}}>
                <p style={{width: "80%"}}> {content}</p></div>

        </div>;
    }

    getCsMessage(content) {
        return <div style={{"margin-top": 12, display: "inline-block", width: "100%"}}>

            <div style={{width: 20, float: "right"}}>
                <img style={{width: 20, height: 20}}
                     src="http://cashmama-oss-pro.cashmama.in/app/customer_orange.png"/>

            </div>

            <div style={{"margin-right": 22, width: "100%", "text-align": "right"}}>
                <p style={{
                    width: "80%",
                    "line-height": 19,
                    "float": "right"
                }}> {content}</p></div>

        </div>;
    }

    render() {
        const {getFieldDecorator} = this.props.form
        let self = this
        let columns = [

            {
                title: 'Date',
                dataIndex: 'date',
            }, {
                title: 'App',
                dataIndex: 'appName',
            }, {
                title: 'Name/Mobile/Email',
                dataIndex: 'name',
                render: (text, record) => {
                    return (
                        <div>
                            {"name: " + record.name}
                            <br/>
                            {"mobile: " + record.mobile}
                            <br/>
                            {"email: " + record.email}
                            <br/>
                        </div>
                    );
                },
            }, {
                title: 'content',
                dataIndex: 'content',
                key: 'content',
                width: "500"
            }, {
                title: 'status',
                dataIndex: 'status',
                render: (text, record) => {
                    return (
                        <div>
                            <a onClick={() => {
                                this.edit(record)
                            }}
                               href='javascript:;'>waiting</a>
                        </div>
                    );
                },
            }
        ]


        return (
            <div>
                <Modal
                    title="Add Records"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText="Send to user"
                    cancelText="ignore"
                >

                    <Form style={{width: '100%', margin: 'auto'}} horizontal>

                        <FormItem>
                            <div style={{
                                maxHeight: "420px",
                                minHeight: "220px",
                                overflow: "scroll",
                                border: "1px solid gray"
                            }}>
                                {this.createDialog()}

                            </div>
                        </FormItem>

                        <br/>
                        <FormItem label="feedbackId" style={{display: "none"}}>
                            {getFieldDecorator('feedbackId', {})(
                                <Input placeholder="required"/>
                            )}
                        </FormItem>

                        <FormItem label=" your replay to customer:">
                            {getFieldDecorator('record', {
                                rules: [
                                    {message: 'your record is necessary!'},
                                ],
                            })(
                                <TextArea
                                    placeholder="required"
                                    autoSize={{minRows: 15, maxRows: 15}}
                                />
                            )}
                        </FormItem>
                    </Form>

                </Modal>

                <div>
                    <Col span={24}>
                        <Table
                            pagination={this.setPagination()}
                            key={(record) => {
                                this.getRowKey(record)
                            }}
                            rowKey={(record) => {
                                this.getRowKey(record)
                            }}
                            bordered
                            dataSource={this.state.feedList}
                            columns={columns}
                            size='small'
                        />
                    </Col>
                </div>
            </div>
        )
    }
}

feedback = Form.create()(feedback)
export default feedback
